<template>
  <view class="container">
    <view class="upload-section">
      <text class="section-title">图片上传</text>
      
      <!-- 选择图片按钮 -->
      <button class="primary-btn" @click="chooseImage">选择图片</button>
      
      <!-- 图片预览区域 -->
      <view class="image-preview" v-if="tempImagePath">
        <image :src="tempImagePath" mode="aspectFit" class="preview-image"></image>
        <button class="delete-btn" @click="deleteImage">删除</button>
      </view>
      
      <!-- 上传进度 -->
      <view class="upload-progress" v-if="uploadProgress > 0 && uploadProgress < 100">
        <text>上传进度: {{ uploadProgress }}%</text>
        <progress :percent="uploadProgress" stroke-width="4" activeColor="#07c160" backgroundColor="#eeeeee"></progress>
      </view>
      
      <!-- 上传按钮 -->
      <button class="primary-btn" @click="uploadImage" :disabled="!tempImagePath || uploadLoading">
        {{ uploadLoading ? '上传中...' : '上传图片' }}
      </button>
      
      <!-- 上传结果 -->
      <view class="upload-result" v-if="uploadResult">
        <text class="section-title">上传结果</text>
        <view class="result-item" v-for="(value, key) in uploadResult" :key="key">
          <text class="item-key">{{ key }}:</text>
          <text class="item-value">{{ value }}</text>
        </view>
      </view>
      
      <!-- 错误提示 -->
      <view class="error" v-if="uploadError">
        <text>{{ uploadError }}</text>
        <button @click="retryUpload">重试</button>
      </view>
      
      <!-- 历史上传记录 -->
      <view class="history-section" v-if="uploadHistory.length > 0">
        <text class="section-title">上传历史</text>
        <view class="history-list">
          <view class="history-item" v-for="(item, index) in uploadHistory" :key="index">
            <image :src="item.url" mode="aspectFit" class="history-image"></image>
            <text class="history-info">{{ item.filename }}</text>
            <text class="history-time">{{ formatDate(item.uploadTime) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { uploadFile } from '../../utils/request'

export default {
  data() {
    return {
      tempImagePath: '', // 临时图片路径
      uploadProgress: 0, // 上传进度
      uploadLoading: false, // 上传加载状态
      uploadError: '', // 上传错误信息
      uploadResult: null, // 上传结果
      uploadHistory: [] // 上传历史记录
    }
  },
  computed: {
    isLogin() {
      return this.$store.state.user.isLogin
    }
  },
  onLoad() {
    if (!this.isLogin) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
    }
    
    // 加载上传历史
    this.loadUploadHistory()
  },
  methods: {
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1, // 只能选择一张图片
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 可从相册和相机选择
        success: (res) => {
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            // 清除之前的错误信息
            this.uploadError = ''
            // 设置临时图片路径
            this.tempImagePath = res.tempFilePaths[0]
          }
        }
      })
    },
    
    // 删除图片
    deleteImage() {
      this.tempImagePath = ''
      this.uploadProgress = 0
      this.uploadResult = null
      this.uploadError = ''
    },
    
    // 上传图片
    uploadImage() {
      if (!this.tempImagePath) {
        uni.showToast({
          title: '请先选择图片',
          icon: 'none'
        })
        return
      }
      
      this.uploadLoading = true
      this.uploadError = ''
      this.uploadProgress = 0
      
      uploadFile('/api/upload/image', this.tempImagePath, {
        name: 'image', // 文件对应的key
        formData: {
          type: 'avatar' // 其他表单参数
        },
        onProgressUpdate: (res) => {
          this.uploadProgress = res.progress
        }
      }).then((res) => {
        this.uploadResult = res.data
        
        // 添加到历史记录
        const historyItem = {
          url: res.data.url,
          filename: res.data.filename,
          uploadTime: new Date().getTime()
        }
        this.uploadHistory.unshift(historyItem)
        
        // 保存历史记录到本地
        this.saveUploadHistory()
        
        // 清除临时图片
        this.tempImagePath = ''
        
        uni.showToast({
          title: '上传成功'
        })
      }).catch((error) => {
        this.uploadError = error.message || '上传失败'
      }).finally(() => {
        this.uploadLoading = false
      })
    },
    
    // 重试上传
    retryUpload() {
      this.uploadImage()
    },
    
    // 加载上传历史
    loadUploadHistory() {
      const history = uni.getStorageSync('uploadHistory')
      if (history) {
        this.uploadHistory = JSON.parse(history)
      }
    },
    
    // 保存上传历史
    saveUploadHistory() {
      // 只保留最近10条记录
      if (this.uploadHistory.length > 10) {
        this.uploadHistory = this.uploadHistory.slice(0, 10)
      }
      uni.setStorageSync('uploadHistory', JSON.stringify(this.uploadHistory))
    },
    
    // 格式化日期
    formatDate(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.upload-section {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.primary-btn {
  background-color: #07c160;
  color: #fff;
  margin-bottom: 20rpx;
}

.image-preview {
  margin: 20rpx 0;
  text-align: center;
}

.preview-image {
  width: 400rpx;
  height: 400rpx;
  margin-bottom: 20rpx;
}

.delete-btn {
  background-color: #f8f8f8;
  color: #e64340;
  font-size: 28rpx;
}

.upload-progress {
  margin: 20rpx 0;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.upload-result {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.result-item {
  display: flex;
  margin-bottom: 10rpx;
}

.item-key {
  font-size: 28rpx;
  color: #666;
  width: 100rpx;
}

.item-value {
  font-size: 28rpx;
  flex: 1;
}

.error {
  text-align: center;
  padding: 20rpx;
  color: #e64340;
}

.history-section {
  margin-top: 40rpx;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
}

.history-item {
  width: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.history-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 10rpx;
}

.history-info {
  font-size: 24rpx;
  color: #666;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-time {
  font-size: 20rpx;
  color: #999;
  display: block;
  margin-top: 5rpx;
}
</style>